<?php
include_once('Sqlexecutor.php');
class User 
{
    private $_dbh;
    private $_logger;

    public function __construct($dbh, $logger = Null)
    {/*{{{*/
        $this->_dbh = $dbh; 
        $this->_logger = $logger; 
    }/*}}}*/

    public function updatePassByID($oldpassword, $password, $username)
    {/*{{{*/
        $sql = "select `password` from bg_user where username = ?";
        $val[] = $username;
        $info = array();
        try
        {
            $info = $this->_dbh->query($sql, $val);
        }
        catch(Exception $e)
        {
            if($this->_logger)
                $this->_logger->error($e->getFile() . ":" . $e->getLine() . "," . $e->getMessage());
            return -100;
        }

        $pass = isset($info['password']) ? $info['password'] : '';
        if(md5($oldpassword) != $pass)
        {
            return -3;
        }

        $sql = 'update bg_user set `password` = ? where `username` = ?';
        $val = array();
        $val[] = md5($password);
        $val[] = $username;
        try
        {
            $this->_dbh->beginTrans();
            $res = $this->_dbh->execute($sql, $val); 
            $this->_dbh->commit();
            
            // 0: not change, 1 : change 1 rows
            return $res;
        }
        catch(Exception $e)
        {
            $this->_dbh->rollback();
            if($this->_logger)
                $this->_logger->error($e->getFile() . ":" . $e->getLine() . "," . $e->getMessage());
            // Unknow error
            return -100;
        }
    }/*}}}*/

    public function login($username, $password)
    {/*{{{*/
        $sql = "select `username` from bg_user where `username` = ? and `password` = ?";
        $val[] = $username;
        $val[] = md5($password);
        $info = array();
        try
        {
            $info = $this->_dbh->query($sql, $val);
            if($info === false)
            {
                return -1;
            }
            return $info;
        }
        catch(Exception $e)
        {
            if($this->_logger)
                $this->_logger->error($e->getFile() . ":" . $e->getLine() . "," . $e->getMessage());
            return -100;
        }
    }/*}}}*/
}

